package cn.com.sina.finance.todolist.activity;

import android.util.Log;
import android.view.View;
import android.widget.EditText;

import org.greenrobot.eventbus.EventBus;

import cn.com.sina.finance.todolist.R;
import cn.com.sina.finance.todolist.base.BaseActivity;
import cn.com.sina.finance.todolist.bean.ApiResponse;
import cn.com.sina.finance.todolist.bean.LoginData;
import cn.com.sina.finance.todolist.event.LoginEvent;
import cn.com.sina.finance.todolist.net.HttpService;
import cn.com.sina.finance.todolist.net.HttpUtil;
import cn.com.sina.finance.todolist.util.SpUtil;
import cn.com.sina.finance.todolist.util.ToastUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class LoginActivity extends BaseActivity {

    private EditText editText_UserName;
    private EditText editText_Password;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        editText_UserName = viewHolder.getView(R.id.editText_UserName);
        editText_Password = viewHolder.getView(R.id.editText_Password);
    }

    @Override
    public void initListener() {
        viewHolder.setOnClickListener(R.id.btnLogin, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login() {
        String userName = editText_UserName.getText().toString();
        String password = editText_Password.getText().toString();

        Retrofit retrofit = HttpUtil.getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<ApiResponse<LoginData>> call = httpService.login(userName, password);
        call.enqueue(new Callback<ApiResponse<LoginData>>() {
            @Override
            public void onResponse(Call<ApiResponse<LoginData>> call, Response<ApiResponse<LoginData>> response) {
                try {
                    ApiResponse<LoginData> apiResponse = response.body();
                    if (apiResponse.success()) {
                        SpUtil.setString(SpUtil.COOKIE, apiResponse.data.token);
                        ToastUtil.showLongToast(LoginActivity.this, "登录成功");
                        EventBus.getDefault().post(new LoginEvent());
                        finish();
                    } else {
                        ToastUtil.showLongToast(LoginActivity.this, apiResponse.msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<LoginData>> call, Throwable throwable) {
                Log.wtf("todo", "网络请求失败", throwable);
                ToastUtil.showLongToast(LoginActivity.this, "网络请求失败" + throwable.getMessage());
            }
        });
    }
}